package com.zaizai.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zaizai.aop.AutoLog;
import com.zaizai.aop.LoginLog;
import com.zaizai.domain.AjaxResult;
import com.zaizai.domain.Role;
import com.zaizai.domain.dto.EmailDto;
import com.zaizai.domain.dto.RegisterDto;
import com.zaizai.properties.JwtProperties;
import com.zaizai.service.IRoleService;
import com.zaizai.utils.BaseContext;
import com.zaizai.utils.JwtUtil;
import com.zaizai.utils.Md5Util;
import com.zaizai.utils.page.TableDataInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.zaizai.domain.AjaxResult.error;
import static com.zaizai.domain.AjaxResult.success;


/**
 * 角色Controller
 *
 * @author zaiZai
 * @date 2024-10-21
 */
@Slf4j
@RestController
@RequestMapping("/role")
public class RoleController extends BaseController {
    @Autowired
    private IRoleService roleService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 重置密码
     */
    @PutMapping("/reset")
    public AjaxResult reset(@RequestBody EmailDto emailDto) {
        log.info("验证码结果为：{}", emailDto.getEmail());
        //从redis中获取邮箱的captcha
        String captcha = redisTemplate.opsForValue().get("resetPasswordCaptcha:" + emailDto.getEmail());
        log.info("验证码结果为：{}", captcha);
        //判断验证码是否正确
        if (captcha == null || !captcha.equals(emailDto.getCaptcha())) {
            return error("验证码错误");
        }
        //根据邮箱查询用户信息
        Role role = roleService.findRoleByEmail(emailDto.getEmail());
        if (role == null) {
            return error("邮箱还未注册，请注册");
        }
        //密码加密
        role.setPassword(Md5Util.getMD5String(emailDto.getPassword()));
        roleService.updateRole(role);
        return success("重置密码成功！");
    }

    /**
     * 通过邮箱进行登录和注册
     */
    @PostMapping("/intoByEmail")
    public AjaxResult intoByEmail(@RequestBody EmailDto emailDto) {
        //从redis中获取邮箱的captcha
        String captcha = redisTemplate.opsForValue().get("captcha:" + emailDto.getEmail());
        //判断验证码是否正确
        if (captcha == null || !captcha.equals(emailDto.getCaptcha())) {
            return error("验证码错误");
        }

        //根据邮箱查询用户信息
        Role role = roleService.findRoleByEmail(emailDto.getEmail());
        //如果用户不存在进行注册
        if (role == null) {
            Role newRole = new Role();
            BeanUtils.copyProperties(emailDto, newRole);
            roleService.insertRole(newRole);
            //注册成功后，获取用户信息
            role = roleService.findRoleByEmail(emailDto.getEmail());
        }
        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", role.getId());
        
        //设置token
        String token = JwtUtil.createJWT(jwtProperties.getSecretKey(), jwtProperties.getTtl(), claims);
        //将token根据用户id存入redis；
        redisTemplate.opsForValue().set("login:" + role.getId(), token);
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("id", role.getId());
        map.put("permission", role.getPermission());
        return success("登录成功", map);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody RegisterDto registerDto) {

        //从redis中获取验证码的key
        String key = "captcha:" + registerDto.getCaptchaKey();
        String captcha = redisTemplate.opsForValue().get(key);
        log.info("验证码结果为：{}", registerDto.getCaptcha());
        //判断验证码是否正确
        if (captcha != null && captcha.equals(registerDto.getCaptcha())) {
            log.info("验证码通过！");
        } else {
            return error("验证码错误");
        }

        Integer result = roleService.register(registerDto);
        //返回注册结果
        if (result == 1) {
            return success();
        } else if (result == -1) {
            return error("密码不一致");
        } else if (result == -2) {
            return error("用户名已经存在");
        } else {
            return error("手机号已经存在");
        }
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @LoginLog("登录")
    public AjaxResult login(@RequestBody RegisterDto registerDto) {
        // 验证用户名密码
        Role user = roleService.login(registerDto);
        
        // 返回登录结果
        if (user != null) {
            // 判断是否有效
            if (user.getIsCan().equals("N")) {
                return error("账号已禁用");
            }
            
            // 登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put("id", user.getId());
            claims.put("sub", String.valueOf(user.getId()));
            
            // 设置token
            String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims
            );
            
            // 将token根据用户id存入redis
            redisTemplate.opsForValue().set("login:" + user.getId(), token);
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("permission", user.getPermission());
            map.put("id", user.getId());
            return success("登录成功",map);
        } else {
            return error("账号或密码错误");
        }
    }

    /**
     * 退出登录
     */
    @DeleteMapping("/logout/{id}")
    @LoginLog("退出")
    public AjaxResult logout(@PathVariable("id") Long id) {
        log.info("退出登录的用户id为：{}", id);
        redisTemplate.delete("login:" + id);
        return success();
    }

    /**
     * 查询角色列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Role role) {
        startPage();
        List<Role> list = roleService.selectRoleList(role);
        return getDataTable(list);
    }

    /**
     * 获取角色详细信息
     */

    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(roleService.selectRoleById(id));
    }

    /**
     * 新增角色
     */

    @PostMapping
    @AutoLog("新增角色信息")
    public AjaxResult add(@RequestBody Role role) {
        return success(roleService.insertRole(role));
    }

    /**
     * 修改角色
     */

    @PutMapping
    @AutoLog("修改角色信息")
    public AjaxResult edit(@RequestBody Role role) {
        return success(roleService.updateRole(role));
    }

    /**
     * 删除角色
     */

    @DeleteMapping("/{ids}")
    @AutoLog("删除角色信息")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return success(roleService.deleteRoleByIds(ids));
    }

    /**
     * 查询当前登录用户信息
     */
    @GetMapping("/info")
    public AjaxResult getInfo() {
        return success(roleService.selectRoleById(BaseContext.getCurrentId()));
    }
}
